package com.ms.utiles;

import com.ms.constant.JwtClaimsConstant;
import com.ms.properties.JwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类 - 兼容旧版本API
 */
@Component
public class JwtUtil {

    private final JwtProperties jwtProperties;

    public JwtUtil(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }

    /**
     * 生成用户令牌
     * @param userId 用户ID
     * @return JWT令牌
     */
    public String createUserToken(Integer userId) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, userId);
        return buildToken(claims, jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl());
    }

    /**
     * 生成管理员令牌
     * @param adminId 管理员ID
     * @param role 管理员角色
     * @return JWT令牌
     */
    public String createAdminToken(Integer adminId, String role) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.ADMIN_ID, adminId);
        claims.put(JwtClaimsConstant.ADMIN_ROLE, role);
        return buildToken(claims, jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl());
    }

    /**
     * 解析JWT令牌
     * @param token 令牌字符串
     * @param secretKey 密钥
     * @return 声明信息
     */
    public Claims parseToken(String token, String secretKey) {
        return Jwts.parser()
                .setSigningKey(secretKey.getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 构建JWT令牌
     */
    private String buildToken(Map<String, Object> claims, String secretKey, long ttlMillis) {
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + ttlMillis))
                .signWith(SignatureAlgorithm.HS256, secretKey.getBytes(StandardCharsets.UTF_8))
                .compact();
    }
}